from django.test import TestCase
from ..models import User
from tasks.models import Tasks
from django.urls import reverse
from tasks.services import initial_tasks
from django.test import Client


class MainViewTest(TestCase):

    def setUp(self):
        user = User.objects.create(email='testUser@email.com', password='12345678')

        initial_tasks(user.email)
        self.user = user
        self.client = Client()

    def test_user_tasks_count(self):
        user_tasks = Tasks.objects.filter(owner=self.user)
        user_tasks_count = user_tasks.count()
        self.assertEqual(user_tasks_count, 40)
        
    def test_view_url_exists_at_desired_location(self):
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, 200)

    def test_redirect_loginpage_if_not_logged_in(self):
        resp = self.client.get(reverse('task:main'))
        self.assertEqual(resp.status_code, 302)

    def test_redirect_loginpage_if_logged_in(self):
        self.client.force_login(user=self.user)
        resp = self.client.get(reverse('task:main'))
        self.assertEqual(resp.status_code, 200)
        self.assertTemplateUsed(resp, 'users/profile.html')

    def test_user_redirect_tasks_count(self):
        self.client.force_login(user=self.user)
        resp = self.client.get(reverse('task:main'))
        self.assertEqual(resp.context['tasks'].count(), 40)
        